﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace ChengNet.StrongCaml
{
    /// <summary>
    /// Provides methods for encoding strings.
    /// </summary>
    public static class Encode
    {
        static IDictionary<string, string> scriptmap = new Dictionary<string, string>() {
           { "\"", "\\\""},
           { @"+", @"\u002b"},
           { @"\", @"\\"},
           { "'", @"\u0027"},
           { ">", @"\u003e"},
           { "<", @"\u003c"},
        };

        /// <summary>
        /// Encodes a string for use in script. Same as <a href="http://msdn.microsoft.com/en-us/library/dd587589%28v=office.11%29.aspx">Microsoft.SharePoint.Utilities.SPEncode.ScriptEncode</a>
        /// </summary>
        public static string ScriptEncode(string str) {
            var escapedKeys = scriptmap.Keys.Select(s => Regex.Escape(s));
            var regex = new Regex(String.Join("|", escapedKeys.ToArray()));
            return regex.Replace(str, m => scriptmap[m.Value]);
        }
    }
}
